package com.apes.hr.entry;

import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.generator.service.SequenceService;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.rop.converter.DateUtils;
import com.apes.framework.util.MapUtil;
import com.apes.framework.util.ReflectUtil;
import com.apes.hr.base.model.Employee;
import com.apes.hr.base.model.EmployeeFamily;
import com.apes.hr.base.model.EmployeeSkillCertificate;
import com.apes.hr.base.repository.EmployeeRepository;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.enumeration.repository.EnumerationRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Title: EntryInformationService
 * @Description:
 * @author: ZhengZeXian
 * @create: 2021/3/12 17:45
 */
@Service("entryInformationService")
public class EntryInformationService extends DomainService {

    @Autowired
    private EnumerationRepository enumerationRepository;
    @Autowired
    private EntryInformationRepository entryInformationRepository;
    @Autowired
    private EmployeeRepository employeeRepository;
    @Autowired
    public SequenceService sequenceService;

    /**
     * 保存
     * @param request
     * @return
     */
    public EntryInformation save(SimpleRequest request){
        EntryInformation entryInformation = request.getO(EntryInformation.class);
        return entryInformationRepository.saveAndFlush(entryInformation);
    }

    /**
     * 修改
     * @param request
     * @return
     */
    public EntryInformation update(SimpleRequest request){
        checkData(request);
        EntryInformation entryInformation = request.getO(EntryInformation.class);
        return entryInformationRepository.saveAndFlush(entryInformation);
    }

    /**
     * 删除
     * @param request
     * @return
     */
    public String delete(SimpleRequest request){
        checkData(request);
        EntryInformation entryInformation = request.getO(EntryInformation.class);
        entryInformationRepository.delete(entryInformation);
        return "删除成功！";
    }

    /**
     * 转审核
     * @param request
     * @return
     */
    public EntryInformation transApprove(SimpleRequest request){
        checkData(request);
        EntryInformation entryInformation = request.getO(EntryInformation.class);
        entryInformation.setState("transApprove");
        return entryInformationRepository.saveAndFlush(entryInformation);
    }

    /**
     * 审核通过
     */
    public EntryInformation approve(SimpleRequest request){
        checkData(request);
        EntryInformation entryInformation = request.getO(EntryInformation.class);
        entryInformation.setState("approve");
        entryInformation.setApproveDate(new Date());
        entryInformation.setApproveId(this.getPerson(request));

        Employee employee = employeeRepository.findOne(entryInformation.getEmployee().getId());
        Set<EmployeeFamily> employeeFamilySet = new HashSet<EmployeeFamily>();
        employeeFamilySet.addAll(employee.getEmployeeFamilies());
        entryInformation.getEntryInformationFamilies().stream().filter(item -> !item.getName().equals("无")).forEach(entry -> {

            //把界面为无的数据过滤掉 判断当前保存的家庭成员的名字+关系+手机号码是否存在于人员档案家庭成员
            if(employee.getEmployeeFamilies().stream().filter(employeeFamily -> employeeFamily.getName().equals(entry.getName())
                    && employeeFamily.getMobileNumber().equals(entry.getMobileNumber())
                    && employeeFamily.getRelation().getDescription().equals(entry.getRelation().getDescription())).collect(Collectors.toList()).size() >= 1){
                return;
            }
            EmployeeFamily employeeFamily = new EmployeeFamily();
            employeeFamily.setId(Long.valueOf(sequenceService.getId(EmployeeFamily.CONST_TABLE_NAME)));
            employeeFamily.setEmployee(employee);
            employeeFamily.setName(entry.getName());
            employeeFamily.setRelation(entry.getRelation());
            employeeFamily.setBirthday(entry.getBirthday());
            employeeFamily.setJobs(entry.getJobs());
            employeeFamily.setWorkUnit(entry.getWorkUnit());
            employeeFamily.setMobileNumber(entry.getMobileNumber());
            employeeFamily.setEntryInfoId(entryInformation.getId());
            employeeFamilySet.add(employeeFamily);
        });
        employee.setEmployeeFamilies(employeeFamilySet);

        //同步技能证书
        Set<EmployeeSkillCertificate> employeeSkillCertificates = employee.getEmployeeSkillCertificates();
        Set<EmployeeSkillCertificate> newEmployeeSkillCertificates = new HashSet<>();
        ReflectUtil.copyAll(employeeSkillCertificates, newEmployeeSkillCertificates);
        if(!entryInformation.getEntryInformationSkills().isEmpty()){
            entryInformation.getEntryInformationSkills().forEach(skill ->{
                EmployeeSkillCertificate certificate = new EmployeeSkillCertificate();
                certificate.setId(Integer.valueOf(SpringManager.getBean(SequenceService.class).getId(certificate.CONST_TABLE_NAME)));
                certificate.setEmployee(employee);
                certificate.setSkillType(skill.getSkillType());
                certificate.setSkillPhotos(skill.getSkillPhotos());
                newEmployeeSkillCertificates.add(certificate);
            });
        }

        //人员档案标记同步
        writeEmployee(entryInformation,employee);

        employee.setEmployeeSkillCertificates(newEmployeeSkillCertificates);
        employeeRepository.saveAndFlush(employee);
        return entryInformationRepository.saveAndFlush(entryInformation);

    }

    /**
     * 根据上传的照片写入人员档案对应的标记
     * @param entryInformation
     * @param employee
     */
    public void writeEmployee(EntryInformation entryInformation,Employee employee){
        if(entryInformation.getIdentityCardPhotos() != null && !employee.isIdCardPhoto()){
            employee.setIdCardPhoto(true);
        }
        if(entryInformation.getIdentityCardPhotosR() != null && !employee.isIdCardPhotoR()){
            employee.setIdCardPhotoR(true);
        }
        if(entryInformation.getDrivingPhotos() != null && !employee.isDriver()){
            employee.setDriver(true);
        }
        if(entryInformation.getDrivingPhotosR() != null && !employee.isDriverR()){
            employee.setDriverR(true);
        }
        if(entryInformation.getBankCardPhotos() != null && !employee.isBankCardPhoto()){
            employee.setBankCardPhoto(true);
        }
        if(entryInformation.getBankCardPhotosR() != null && !employee.isBankCardPhotosR()){
            employee.setBankCardPhotosR(true);
        }
        if(entryInformation.getOneInchPhotos() != null && !employee.isOneInchPhoto()){
            employee.setOneInchPhoto(true);
        }
        if(entryInformation.getPhysicalPhotos() != null && !employee.isMedical()){
            employee.setMedical(true);
        }
        if(entryInformation.getJobPhotos() != null && !employee.isJobPhoto()){
            employee.setJobPhoto(true);
        }
        if(entryInformation.getQuitPhotos() != null && !employee.isQuitPhoto()){
            employee.setQuitPhoto(true);
        }
        if(entryInformation.getDiplomaPhotos() != null && !employee.isDiploma()){
            employee.setDiploma(true);
        }
        if(entryInformation.getVeteranPhotos() != null && !employee.isVeteranPhoto()){
            employee.setVeteranPhoto(true);
        }
        if(entryInformation.getHandicappedPhotos() != null && !employee.isHandicappedPhoto()){
            employee.setHandicappedPhoto(true);
        }
        if(entryInformation.getDiseasePhotos() != null && !employee.isCoinSpray()){
            employee.setCoinSpray(true);
        }
        if(entryInformation.getOtherProvePhotos() != null && !employee.isPhoto()){
            employee.setPhoto(true);
        }
    }

    /**
     * 审核拒绝
     */
    public EntryInformation refuse(SimpleRequest request) {
        checkData(request);
        EntryInformation entryInformation = request.getO(EntryInformation.class);
        entryInformation.setState("create");
        return entryInformationRepository.saveAndFlush(entryInformation);
    }

    /**
     * 检查数据判断，判读当前的输入版本信息
     * @param request
     */
    public void checkData(SimpleRequest request){
        String id = request.get("id");
        int version = request.get("version");

        // 从数据库中取数，检查数据
        EntryInformation entryInformation = entryInformationRepository.findOne(id);
        if (entryInformation == null) throw new RuntimeException("入职资料补充单号【" + id + "】在系统中不存在。");
        if (entryInformation.getVersion() != version) throw new RuntimeException("记录已更新或已删除，请重新提交！");
    }

    /**
     * 获取家庭成员五种关系 前台展示 固定
     * @return
     */
    public List<EntryInformationFamily> getRelationForUI(){
        List<EntryInformationFamily> entryInformationFamilies = new ArrayList<>();
        Enumeration father = enumerationRepository.findByTypeAndValue("父亲", "relation");
        Enumeration mom = enumerationRepository.findByTypeAndValue("母亲", "relation");
        Enumeration wife = enumerationRepository.findByTypeAndValue("夫妻", "relation");
        Enumeration brother = enumerationRepository.findByTypeAndValue("兄弟", "relation");
        Enumeration sister = enumerationRepository.findByTypeAndValue("姐妹", "relation");
        EntryInformationFamily one = new EntryInformationFamily();
        one.setName("无");
        one.setWorkUnit("无");
        one.setJobs("无");
        one.setBirthday(DateUtils.parseDate("1800-01-01","yyyy-MM-dd"));
        one.setMobileNumber("xxx-xxxx-xxxx");
        one.setRelation(father);
        EntryInformationFamily two = new EntryInformationFamily();
        two.setName("无");
        two.setWorkUnit("无");
        two.setJobs("无");
        two.setBirthday(DateUtils.parseDate("1800-01-01","yyyy-MM-dd"));
        two.setMobileNumber("xxx-xxxx-xxxx");
        two.setRelation(mom);
        EntryInformationFamily three = new EntryInformationFamily();
        three.setName("无");
        three.setWorkUnit("无");
        three.setJobs("无");
        three.setBirthday(DateUtils.parseDate("1800-01-01","yyyy-MM-dd"));
        three.setMobileNumber("xxx-xxxx-xxxx");
        three.setRelation(wife);
        EntryInformationFamily four = new EntryInformationFamily();
        four.setName("无");
        four.setWorkUnit("无");
        four.setJobs("无");
        four.setBirthday(DateUtils.parseDate("1800-01-01","yyyy-MM-dd"));
        four.setMobileNumber("xxx-xxxx-xxxx");
        four.setRelation(brother);
        EntryInformationFamily five = new EntryInformationFamily();
        five.setName("无");
        five.setWorkUnit("无");
        five.setJobs("无");
        five.setBirthday(DateUtils.parseDate("1800-01-01","yyyy-MM-dd"));
        five.setMobileNumber("xxx-xxxx-xxxx");
        five.setRelation(sister);
        entryInformationFamilies.add(one);
        entryInformationFamilies.add(two);
        entryInformationFamilies.add(three);
        entryInformationFamilies.add(four);
        entryInformationFamilies.add(five);
        return entryInformationFamilies;
    }

    /**
     * 根据人员查找入职资料补充单
     * @param request
     * @return
     */
    public List<Map> findByEmployee(SimpleRequest request){
        List<EntryInformation> entryInformations = entryInformationRepository.findByStateAndEmployeeIdOrderByApproveDateDesc("approve", request.get("employeeId"));

        List<Map> maps = new ArrayList<Map>();

        maps.add(packMapData("身份证正面",fileStr(entryInformations.stream().map(EntryInformation::getIdentityCardPhotos).filter(Objects::nonNull).collect(Collectors.toList()))));
        maps.add(packMapData("身份证反面",fileStr(entryInformations.stream().map(EntryInformation::getIdentityCardPhotosR).filter(Objects::nonNull).collect(Collectors.toList()))));
        maps.add(packMapData("银行卡正面",fileStr(entryInformations.stream().map(EntryInformation::getBankCardPhotos).filter(Objects::nonNull).collect(Collectors.toList()))));
        maps.add(packMapData("银行卡反面",fileStr(entryInformations.stream().map(EntryInformation::getBankCardPhotosR).filter(Objects::nonNull).collect(Collectors.toList()))));
        maps.add(packMapData("驾驶证正面",fileStr(entryInformations.stream().map(EntryInformation::getDrivingPhotos).filter(Objects::nonNull).collect(Collectors.toList()))));
        maps.add(packMapData("驾驶证反面",fileStr(entryInformations.stream().map(EntryInformation::getDrivingPhotosR).filter(Objects::nonNull).collect(Collectors.toList()))));
        maps.add(packMapData("体检报告",fileStr(entryInformations.stream().map(EntryInformation::getPhysicalPhotos).filter(Objects::nonNull).collect(Collectors.toList()))));
        maps.add(packMapData("职业资格证",fileStr(entryInformations.stream().map(EntryInformation::getJobPhotos).filter(Objects::nonNull).collect(Collectors.toList()))));
        maps.add(packMapData("白底一寸照片",fileStr(entryInformations.stream().map(EntryInformation::getOneInchPhotos).filter(Objects::nonNull).collect(Collectors.toList()))));
        maps.add(packMapData("毕业证",fileStr(entryInformations.stream().map(EntryInformation::getDiplomaPhotos).filter(Objects::nonNull).collect(Collectors.toList()))));
        maps.add(packMapData("退伍军人证",fileStr(entryInformations.stream().map(EntryInformation::getVeteranPhotos).filter(Objects::nonNull).collect(Collectors.toList()))));
        maps.add(packMapData("残疾人证",fileStr(entryInformations.stream().map(EntryInformation::getHandicappedPhotos).filter(Objects::nonNull).collect(Collectors.toList()))));
        maps.add(packMapData("职业病因素体检报告",fileStr(entryInformations.stream().map(EntryInformation::getDiseasePhotos).filter(Objects::nonNull).collect(Collectors.toList()))));
        maps.add(packMapData("其它证明照片",fileStr(entryInformations.stream().map(EntryInformation::getOtherProvePhotos).filter(Objects::nonNull).collect(Collectors.toList()))));

//        EntryInformation entryInformation = new EntryInformation();
//        if (!entryInformations.isEmpty()){
//            entryInformations.stream().forEach(s -> {
//                if (entryInformation.getIdentityCardPhotos() == null) entryInformation.setIdentityCardPhotos(s.getIdentityCardPhotos());
//                if (entryInformation.getIdentityCardPhotosR() == null) entryInformation.setIdentityCardPhotosR(s.getIdentityCardPhotosR());
//                if (entryInformation.getBankCardPhotos() == null) entryInformation.setBankCardPhotos(s.getBankCardPhotos()e);
//                if (entryInformation.getBankCardPhotosR() == null) entryInformation.setBankCardPhotosR(s.getBankCardPhotosR());
//                if (entryInformation.getDrivingPhotos() == null) entryInformation.setDrivingPhotos(s.getDrivingPhotos());
//                if (entryInformation.getDrivingPhotosR() == null) entryInformation.setDrivingPhotosR(s.getDrivingPhotosR());
//                if (entryInformation.getJobPhotos() == null) entryInformation.setJobPhotos(s.getJobPhotos());
//                if (entryInformation.getOneInchPhotos() == null) entryInformation.setOneInchPhotos(s.getOneInchPhotos());
//                if (entryInformation.getPhysicalPhotos() == null) entryInformation.setPhysicalPhotos(s.getPhysicalPhotos());
//                if (entryInformation.getQuitPhotos() == null) entryInformation.setQuitPhotos(s.getQuitPhotos());
//                if (entryInformation.getDiplomaPhotos() == null) entryInformation.setDiplomaPhotos(s.getDiplomaPhotos());
//                if (entryInformation.getVeteranPhotos() == null) entryInformation.setVeteranPhotos(s.getVeteranPhotos());
//                if (entryInformation.getHandicappedPhotos() == null) entryInformation.setHandicappedPhotos(s.getHandicappedPhotos());
//                if (entryInformation.getDiseasePhotos() == null) entryInformation.setDiseasePhotos(s.getDiseasePhotos());
//                if (entryInformation.getOtherProvePhotos() == null) entryInformation.setOtherProvePhotos(s.getOtherProvePhotos());
//            });
//        }
        return maps;
    }

    /**
     * 拼接文件路径
     */
    public String fileStr(List<String> list){
        StringBuilder str = new StringBuilder();
        str.append("[");
        list.stream().forEach(s -> {
            str.append(s.replaceAll("\\[","").trim().replaceAll("\\]","").trim()).append(",");
        });
        if (str.lastIndexOf(",") != -1){
            str.deleteCharAt(str.lastIndexOf(","));
        }
        str.append("]");
        return str.toString();
    }

    public Map packMapData(String typeName,String data){
        return MapUtil.mapper(
                "type",typeName,
                "fileUrl",data
        );
    }

    /**
     * 根据ID 查找
     */
    public EntryInformation findFamilyById(SimpleRequest request){
        Map map = request.getMap();
        String id = "";
        if(map.containsKey("entryInfoId")){
            id = (String) map.get("entryInfoId");
        }else if(map.containsKey("node")){
            JSONObject node = (JSONObject) map.get("node");
            id = (String) node.get("ID");
        }
        EntryInformation entryInformation = entryInformationRepository.findOne(id);
        return entryInformation;
    }

}
